package cc.siyecao.fastdfs.command.storage;

import cc.siyecao.fastdfs.extception.FastDfsException;
import cc.siyecao.fastdfs.model.RecvPackageInfo;
import cc.siyecao.fastdfs.protocol.ProtocolConstants;
import cc.siyecao.fastdfs.util.BytesUtil;
import cc.siyecao.fastdfs.util.ProtocolUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * 文件Truncate命令
 *
 * @author lyt
 */
public class TruncateCommand extends FdfsStorageCommand<Integer> {
    /**
     * TruncateCommand
     *
     * @param appenderFileName
     * @param truncatedFileSize
     */
    public TruncateCommand(String groupName, String appenderFileName, long truncatedFileSize) {
        this.groupName = groupName;
        this.fileName = appenderFileName;
        this.fileSize = truncatedFileSize;
    }

    @Override
    protected void send(OutputStream out, Charset charset) throws Exception {
        if ((groupName == null || groupName.length() == 0) || (fileName == null || fileName.length() == 0)) {
            this.errno = ProtocolConstants.ERR_NO_EINVAL;
            throw new FastDfsException( "groupName and appenderFileName can not be null" );
        }
        byte[] header;
        byte[] hexLenBytes;
        byte[] appenderFilenameBytes;
        int offset;
        int bodyLen;
        appenderFilenameBytes = fileName.getBytes( charset );
        bodyLen = 2 * ProtocolConstants.FDFS_PROTO_PKG_LEN_SIZE + appenderFilenameBytes.length;

        header = ProtocolUtil.packHeader( STORAGE_PROTO_CMD_TRUNCATE_FILE, bodyLen, (byte) 0 );
        byte[] wholePkg = new byte[header.length + bodyLen];
        System.arraycopy( header, 0, wholePkg, 0, header.length );
        offset = header.length;

        hexLenBytes = BytesUtil.long2buff( fileName.length() );
        System.arraycopy( hexLenBytes, 0, wholePkg, offset, hexLenBytes.length );
        offset += hexLenBytes.length;

        hexLenBytes = BytesUtil.long2buff( fileSize );
        System.arraycopy( hexLenBytes, 0, wholePkg, offset, hexLenBytes.length );
        offset += hexLenBytes.length;

        System.arraycopy( appenderFilenameBytes, 0, wholePkg, offset, appenderFilenameBytes.length );
        offset += appenderFilenameBytes.length;

        out.write( wholePkg );
    }

    @Override
    protected Integer receive(InputStream in, Charset charset) throws Exception {
        RecvPackageInfo pkgInfo = ProtocolUtil.recvPackage( in, STORAGE_PROTO_CMD_RESP, 0 );
        this.errno = pkgInfo.errno;
        if (pkgInfo.errno != 0) {
            return Integer.valueOf( this.errno );
        }
        return 0;
    }
}
